#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复Django模板中for循环的{% else %}为{% empty %}
"""
import os
import re
from pathlib import Path


def fix_for_else_to_empty(file_path):
    """将for循环中的{% else %}替换为{% empty %}"""
    print(f"检查: {file_path}")
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    original_content = content
    
    # 查找{% for %}...{% else %}...{% endfor %}模式
    # 使用更精确的多行正则表达式
    lines = content.split('\n')
    fixed_lines = []
    in_for_loop = 0
    
    for i, line in enumerate(lines):
        # 检测{% for %}标签
        if re.search(r'{%\s*for\s+', line):
            in_for_loop += 1
        
        # 检测{% endfor %}标签
        if re.search(r'{%\s*endfor\s*%}', line):
            in_for_loop -= 1
        
        # 如果在for循环内且发现{% else %}
        if in_for_loop > 0 and re.search(r'{%\s*else\s*%}', line):
            # 检查这不是if-else的else
            # 简单方法：查看前面几行是否有未闭合的if
            has_unclosed_if = False
            for j in range(max(0, i-10), i):
                if re.search(r'{%\s*if\s+', lines[j]):
                    # 检查是否已经有endif
                    endif_count = 0
                    for k in range(j, i):
                        if re.search(r'{%\s*endif\s*%}', lines[k]):
                            endif_count += 1
                    if_count = len(re.findall(r'{%\s*if\s+', '\n'.join(lines[j:i])))
                    if if_count > endif_count:
                        has_unclosed_if = True
                        break
            
            if not has_unclosed_if:
                # 这是for循环的else，替换为empty
                line = re.sub(r'{%\s*else\s*%}', '{% empty %}', line)
                print("  → 第" + str(i+1) + "行: 将{% else %}替换为{% empty %}")
        
        fixed_lines.append(line)
    
    content = '\n'.join(fixed_lines)
    
    if content != original_content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"✓ 已修复: {file_path}")
        return True
    else:
        print(f"- 无需修复: {file_path}")
        return False


def process_all_templates(templates_dir):
    """处理所有模板文件"""
    templates_path = Path(templates_dir)
    
    if not templates_path.exists():
        print("错误: 模板目录不存在: " + str(templates_dir))
        return
    
    html_files = list(templates_path.rglob('*.html'))
    total_files = len(html_files)
    fixed_files = 0
    
    print("\n找到 " + str(total_files) + " 个HTML模板文件")
    print("=" * 60)
    
    for html_file in html_files:
        if fix_for_else_to_empty(html_file):
            fixed_files += 1
    
    print("=" * 60)
    print("\n处理完成!")
    print("总文件数: " + str(total_files))
    print("已修复: " + str(fixed_files))
    print("无需修复: " + str(total_files - fixed_files))


if __name__ == '__main__':
    project_root = Path(__file__).parent
    templates_dir = project_root / 'templates'
    
    print("=" * 60)
    print("Django模板for-else修复工具")
    print("=" * 60)
    
    process_all_templates(templates_dir)
    
    print("\n✅ 所有模板文件已处理完成!")
